package com.mentalhealthplatform.studentV3.service;

import com.mentalhealthplatform.appModels.CarouselItem;
import com.mentalhealthplatform.global.redisGuard.CacheService;
import com.mentalhealthplatform.studentV3.repository.CarouselItemRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author Pear
 */
@Service
public class CarouselItemService {

    @Autowired
    private CarouselItemRepository carouselItemRepository;

    @Autowired
    private CacheService cacheService;

    private static final String CAROUSEL_CACHE_KEY = "carousel_items";

    /**
     * 获取所有轮播图项目，优先从 Redis 缓存中获取，若缓存不存在则访问数据库并更新缓存。
     *
     * @return 轮播图项目列表
     */
    public List<CarouselItem> getAllCarouselItems() {
        // 从缓存中获取数据
        List<CarouselItem> carouselItems = cacheService.getCacheData(CAROUSEL_CACHE_KEY, List.class);

        if (carouselItems == null || carouselItems.isEmpty()) {
            // 缓存中不存在，查询数据库
            carouselItems = carouselItemRepository.findAll();

            if (carouselItems == null || carouselItems.isEmpty()) {
                // 如果数据库中也没有数据，缓存空对象以防止缓存穿透
                cacheService.setCacheData(CAROUSEL_CACHE_KEY, List.of(), 60, TimeUnit.SECONDS); // 缓存空列表，设置短时过期
                return List.of(); // 返回空列表
            }

            // 将数据库查询结果写入缓存，设置随机过期时间防止缓存雪崩
            cacheService.setCacheData(CAROUSEL_CACHE_KEY, carouselItems, 300 + new java.util.Random().nextInt(100), TimeUnit.SECONDS);
        }

        return carouselItems;
    }

    /**
     * 清理缓存（在涉及轮播图数据更新、删除等操作时调用）。
     */
    public void clearCarouselCache() {
        cacheService.setCacheData(CAROUSEL_CACHE_KEY, null, 0, TimeUnit.SECONDS);
    }
}